package gov.pbc.gx.nn.pz.impl;

import gov.pbc.gx.nn.pz.dao.BwpzDao;
import gov.pbc.gx.nn.pz.entity.Account;
import gov.pbc.gx.nn.pz.entity.HcBwpz;
import gov.pbc.gx.nn.pz.entity.HcXjpz;
import gov.pbc.gx.nn.pz.entity.HcpzXY;
import gov.pbc.gx.nn.pz.entity.PzFont;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.variant.Record;
import com.bstek.dorado.web.DoradoContext;

/**
 * 
 * @author jack.zhao 本类主要实现bwpz业务逻辑的操作
 * 
 */

@Component("bwpzPR")
public class BwpzPR {
	private static final Integer PZ_CODE_ = 7;
	private static final Integer Font_Size = 16;
	@Resource
	@Autowired
	private BwpzDao bwpzDao;

	/**
	 * 获取表外凭证数据信息
	 */
	@Transactional
	@DataProvider
	public Record getBwpzs() {
		try {
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				return null;
			if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0)
				return null;
			Record record = new Record();
			record.put("pzdate", new Date());
			ArrayList<HcBwpz> lists = (ArrayList<HcBwpz>) bwpzDao.getMuByDeptName();
			if (lists.isEmpty()) {
				HcBwpz e = new HcBwpz();
				// e.setDeptId(bwpzDao.getDeptId());
				e.setPzDate(new Date());
				e.setPzTemplate("新建模板");
				e.setIsSign(1);
				e.setSfMark("0");
				lists.add(e);
				record.put("bwpz", lists);
			} else {
				lists.get(0).setPzDate(new Date());
				record.put("bwpz", lists);
			}
			// List<Record> pys = new ArrayList<Record>();
			// Map<String, Record> pym = new HashMap<String, Record>();
			// Record recordpy = new Record();

			List<HcpzXY> bwpzXYs = bwpzDao.getHcPzXYs(PZ_CODE_);
			if (bwpzXYs != null && !bwpzXYs.isEmpty()) {
				record.put("pys", bwpzXYs);
			} else {

				bwpzXYs = new ArrayList<HcpzXY>();
				HcpzXY bwpzXY = new HcpzXY();
				bwpzXY.setProperty("页边距", 50, 50, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setId(UUID.randomUUID().toString());
				bwpzXY.setProperty("年", 255, 75, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("月", 325, 75, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("日", 385, 75, Font_Size);
				bwpzXYs.add(bwpzXY);

				/*
				 * bwpzXY = new HcpzXY(); bwpzXY.setProperty("流水号", 545, 75);
				 * bwpzXYs.add(bwpzXY);
				 */

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("表外账户名称", 155, 110, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("表外账户帐号", 155, 160, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("附件数量", 705, 260, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("摘要", 80, 290, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("小写金额", 684, 230, Font_Size);
				bwpzXYs.add(bwpzXY);

				bwpzXY = new HcpzXY();
				bwpzXY.setProperty("收付标志", 180, 220, Font_Size);
				bwpzXYs.add(bwpzXY);

			}

			record.put("pys", bwpzXYs);

			// PzFont pzFont = bwpzDao.getFont(PZ_CODE_);
			// if (pzFont == null) {
			// Collection<PzFont> fontLists = new ArrayList<PzFont>();
			// PzFont arrayFont = new PzFont();
			// arrayFont.setCnFont("新宋体");
			// arrayFont.setNumFont("微软雅黑");
			// fontLists.add(arrayFont);
			//
			// // record.put("fontzh", "新宋体");
			// // record.put("fonten", "微软雅黑");
			// // record.put("fontid", null);
			// } else {
			//
			// Collection<PzFont> fontLists = new ArrayList<PzFont>();
			// PzFont arrayFont = new PzFont();
			// arrayFont.setCnFont(pzFont.getCnFont());
			// arrayFont.setNumFont(pzFont.getNumFont());
			// fontLists.add(arrayFont);
			// // record.put("fontzh", pzFont.getCnFont());
			// // record.put("fonten", pzFont.getNumFont());
			// // record.put("fontid", pzFont.getId());
			// }

			return record;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	// var param = {
	// zzpz : view.get("#dataSetxjpz.data.zzpz.current"),
	// pzdate : view.get("#dataSetxjpz.data.pzdate"),
	// pym : view.get("#dataSetxjpz.data.pym"),
	// fontzh : view.get("#dataSetxjpz.data.fontzh"),
	// fonten : view.get("#dataSetxjpz.data.fonten")
	// }

	/**
	 * 设置打印图片的 数据
	 * 
	 * @param graphics
	 * @param param
	 */
	@SuppressWarnings("unchecked")
	private void setImageData(Graphics2D graphics, Map<String, Object> param) {
		try {
			HcBwpz hcBwpz = (HcBwpz) param.get("bwpz");

			Date pzdate = (Date) param.get("pzdate");
			int pyx = (int) Integer.parseInt(param.get("x").toString());
			int pyy = (int) Integer.parseInt(param.get("y").toString());
			String fontzh = param.get("fontzh").toString();
			String fonten = param.get("fonten").toString();
			// int pyx = 0, pyy = 0;
			// x = 0;
			// y = 0;
			// Map<String, Object> pym = (Map<String, Object>) param.get("pym");
			graphics.setBackground(Color.WHITE);
			graphics.setColor(Color.BLACK);
			// Font zhFont = new Font(fontzh, Font.PLAIN, 16);
			// Font enFont = new Font(fonten, Font.PLAIN, 16);
			List<HcpzXY> hcpzxys = (List<HcpzXY>) param.get("pys");
			for (HcpzXY pym : hcpzxys) {

				int fontSize = pym.getFontSize();
				Font zhFont = new Font(fontzh, Font.PLAIN, fontSize);
				Font enFont = new Font(fonten, Font.PLAIN, fontSize);

				graphics.setFont(enFont);
				int x = pym.getX() + pyx;
				int y = pym.getY() + pyy;
				String lable = pym.getLabel();
				if (pzdate != null) {
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(pzdate);
					if (lable.equals("年")) {
						graphics.drawString(String.format("%04d", calendar.get(Calendar.YEAR)), x, y);
					}
					if (lable.equals("月")) {
						graphics.drawString(String.format("%02d", calendar.get(Calendar.MONTH) + 1), x, y);
					}
					if (lable.equals("日")) {
						graphics.drawString(String.format("%02d", calendar.get(Calendar.DATE)), x, y);
					}

				}
				if (hcBwpz != null) {
					/*
					 * if (lable.equals("流水号")) { if (hcBwpz.getSerialnumber()
					 * != null) { graphics.setFont(enFont);
					 * graphics.drawString(hcBwpz.getSerialnumber(), x, y); } }
					 */
					if (lable.equals("表外账户名称")) {
						if (hcBwpz.getCompanyName() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcBwpz.getCompanyName(), x, y);
						}
					}
					if (lable.equals("表外账户帐号")) {
						if (hcBwpz.getCompanyAccount() != null) {
							graphics.setFont(zhFont);
							graphics.drawString(hcBwpz.getCompanyAccount(), x, y);
						}
					}
					if (lable.equals("附件数量")) {
						graphics.setFont(enFont);
						if (hcBwpz.getAttachmentCount() != null) {
							graphics.drawString(String.valueOf(hcBwpz.getAttachmentCount()), x, y);
						}
					}
					if (lable.equals("摘要")) {
						if (hcBwpz.getRemark() != null) {
							graphics.setFont(zhFont);
							String[] strs = hcBwpz.getRemark().split("\n");
							for (int i = 0; i < strs.length; i++) {
								graphics.drawString(strs[i], x + 10, y + i * zhFont.getSize());
							}
						}
					}
					if (lable.equals("小写金额")) {
						graphics.setFont(enFont);
						DecimalFormat df = new DecimalFormat(".00");

						char[] chars;
						int endX = x;
						if (hcBwpz.getAmountNum() != null) {
							if (hcBwpz.getIsSign() == 0) {
								chars = (df.format(hcBwpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 15 - i / 5, y);
								}
							}
							if (hcBwpz.getIsSign() == 1) {
								chars = ("¥" + df.format(hcBwpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 15 - i / 5, y);
								}
							}
							if (hcBwpz.getIsSign() == 2) {
								chars = ("HKD" + df.format(hcBwpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 15 - i / 5, y);
								}
							}
							if (hcBwpz.getIsSign() == 3) {
								chars = ("USD" + df.format(hcBwpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 15 - i / 5, y);
								}
							}
							if (hcBwpz.getIsSign() == 4) {
								chars = (df.format(hcBwpz.getAmountNum()).replace(".", "")).toCharArray();
								for (int i = 0; i < chars.length; i++) {
									graphics.drawString(chars[chars.length - i - 1] + "", endX - i * 15 - i / 5, y);
								}
							}
						}

					}
					if (lable.equals("收付标志")) {
						graphics.setFont(enFont);
						char chars = '√';
						if (hcBwpz.getSfMark().equals("1")) {
							graphics.drawString(chars + "", x, y);
						}
						if (hcBwpz.getSfMark().equals("2")) {
							graphics.drawString(chars + "", x + 110, y);
						}
						if (hcBwpz.getSfMark().equals("0")) {

						}
					}
				}

			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/**
	 * 获取要打印的图片
	 * 
	 * @param param
	 * @return
	 */
	@Expose
	public String getPrintImageAll(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", 0);
			param.put("y", 0);
			BufferedImage imagepz = ImageIO.read(new File(DoradoContext.getCurrent().getServletContext().getRealPath("pz/bwpz.jpg")));
			Graphics2D graphicspz = (Graphics2D) imagepz.getGraphics();
			setImageData(graphicspz, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/all_" + loginuser.getUsername() + ".png";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagepz, "png", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public String getPrintImageData(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", -28);
			param.put("y", -40);
			BufferedImage imagedata = ImageIO.read(new File(DoradoContext.getCurrent().getServletContext().getRealPath("pz/bwpz.jpg")));
			// System.out.println(imagepz.getWidth()*1.0/96.0*24.5);
			// BufferedImage imagedata= new BufferedImage(imagepz.getWidth(),
			// imagepz.getHeight(), imagepz.getType());
			Graphics2D graphicsdata = (Graphics2D) imagedata.getGraphics();
			graphicsdata.setBackground(Color.WHITE);

			// 打印背景图片
			graphicsdata.clearRect(0, 0, imagedata.getWidth(), imagedata.getHeight());
			setImageData(graphicsdata, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/data_" + loginuser.getUsername() + ".jpg";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagedata, "jpg", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public Map<String, Object> getUserInfo() {
		IUser loginuser = ContextHolder.getLoginUser();
		Map<String, Object> userinfo = new HashMap<String, Object>();
		if (loginuser == null) {
			userinfo.put("cname", "");
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("cname", loginuser.getCname());
		if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0) {
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("dept", loginuser.getDepts().get(0).getName());
		return userinfo;
	}

	@DataProvider
	public Collection<HcBwpz> getTypeByGroup() {

		ArrayList<HcBwpz> xjpzs = new ArrayList<HcBwpz>();
		xjpzs = (ArrayList<HcBwpz>) bwpzDao.getOneGroupByType();
		for (int i = 0; i < xjpzs.size(); i++) {
			xjpzs.get(i).setPzDate(new Date());
		}
		return xjpzs;

		// return bwpzDao.getOneGroupByType();

	}

	@SuppressWarnings("unused")
	@DataProvider
	public Collection<HcBwpz> getTepementNameByType(Map<String, Object> param) {
		if (param == null) {
			return null;
		}
		String type = (String) param.get("type");

		ArrayList<HcBwpz> xjpzs = new ArrayList<HcBwpz>();
		xjpzs = (ArrayList<HcBwpz>) bwpzDao.getCoByType(type);
		for (int i = 0; i < xjpzs.size(); i++) {
			xjpzs.get(i).setPzDate(new Date());
		}
		return xjpzs;

		// return bwpzDao.getCoByType(type);
	}

	@Expose
	public HcBwpz ajaxselectOneByTypeAndTemplate(Map<String, Object> param) {
		String type = (String) param.get("type");
		String pztemplate = (String) param.get("pzTemplate");
		if (type == null || pztemplate == null) {
			return null;
		}

		HcBwpz pz = bwpzDao.selectOneByTypeAndTemplate(type, pztemplate);
		pz.setPzDate(new Date());
		return pz;

		// return bwpzDao.selectOneByTypeAndTemplate(type, pztemplate);

	}

	@DataProvider
	public List<Record> getFonts() {
		return bwpzDao.getFonts();
	}

	@DataProvider
	public PzFont getFont() {
		return bwpzDao.getFont(PZ_CODE_);
	}

	@Transactional
	@DataResolver
	public void saveBwpz(HcBwpz hcBwpz) {

		bwpzDao.saveBwpz(hcBwpz);
	}

	@Transactional
	@DataResolver
	public void savepzXY(Collection<HcpzXY> hcbwpzxys) {
		bwpzDao.saveBwpzXY(hcbwpzxys);

	}

	@Transactional
	@DataResolver
	public void saveFont(PzFont pzFont) throws Exception {
		bwpzDao.updateFont(pzFont);
	}

	@Expose
	public void deleteTemplateById(String id) {
		if (StringUtils.isEmpty(id)) {
			return;
		}
		bwpzDao.deleteTemplateById(id);
	}

	@Expose
	public Account ajaxActionGetName(Map<String, Object> parameter) {
		String account = (String) parameter.get("account");
		return bwpzDao.getAccountName(account);

	}

	@Expose
	public boolean updateTempalteName(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String pzTemplate = (String) parameter.get("pzTemplate");
		return bwpzDao.updateTemplateNameDao(pzTemplate, id);
	}

	@Expose
	public boolean updateTempalteType(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String type = (String) parameter.get("type");
		return bwpzDao.updateTemplateTypeDao(type, id);
	}

}
